#!/bin/bash
#
# Copyright(c) 2012-2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
#

. $(dirname $3)/conf_framework

check() {
	cur_name=$(basename $2)
	config_file_path=$1
	if compile_module $cur_name "vm_munmap(0, 0); MAP_PRIVATE;" "linux/mm.h"
	then
		echo $cur_name "1" >> $config_file_path
	elif compile_module $cur_name "do_munmap(NULL, 0)" "linux/mm.h"
	then
		echo $cur_name "2" >> $config_file_path
	elif compile_module $cur_name "vm_munmap(0, 0); MAP_PRIVATE;" "linux/mm.h"\
		"uapi/linux/mman.h"
	then
		echo $cur_name "3" >> $config_file_path
	else
        echo $cur_name "X" >> $config_file_path
    fi
}

apply() {
    case "$1" in
    "1")
		add_function "
#include <uapi/asm-generic/mman-common.h>
	static inline unsigned long cas_vm_mmap(struct file *file,
			unsigned long addr, unsigned long len)
	{
		return vm_mmap(file, addr, len, PROT_READ | PROT_WRITE,
			MAP_ANONYMOUS | MAP_PRIVATE, 0);
	}"
		add_function "
	static inline int cas_vm_munmap(unsigned long start, size_t len)
	{
		return vm_munmap(start, len);
	}" ;;
    "2")
		add_function "
#include <asm-generic/mman-common.h>
	static inline unsigned long cas_vm_mmap(struct file *file,
			unsigned long addr, unsigned long len)
	{
		return do_mmap_pgoff(file, addr, len, PROT_READ | PROT_WRITE,
			MAP_ANONYMOUS | MAP_PRIVATE, 0);
	}"
		add_function "
	static inline int cas_vm_munmap(unsigned long start, size_t len)
	{
		return do_munmap(current->mm, start, len);
	}" ;;
     "3")
		add_function "
#include <uapi/asm-generic/mman-common.h>
#include <uapi/linux/mman.h>
	static inline unsigned long cas_vm_mmap(struct file *file,
			unsigned long addr, unsigned long len)
	{
		return vm_mmap(file, addr, len, PROT_READ | PROT_WRITE,
			MAP_ANONYMOUS | MAP_PRIVATE, 0);
	}"
		add_function "
	static inline int cas_vm_munmap(unsigned long start, size_t len)
	{
		return vm_munmap(start, len);
	}" ;;
    *)
        exit 1
    esac
}

conf_run $@
